﻿using Newtonsoft.Json.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace DeployTool.Core
{
    public class Tool
    {
        /// <summary>
        /// 获取部署程序根路径
        /// </summary>
        public static string GetRootDir()
        {
            return Path.GetDirectoryName(typeof(Program).Assembly.Location);
        }

        /// <summary>
        /// 执行程序,无返回结果
        /// </summary>
        /// <param name="filePath">程序路径</param>
        /// <param name="args">程序参数</param>
        public static void StartProgramWithNoResult(string filePath, string args = "")
        {
            Process process = new Process();
            process.StartInfo.FileName = filePath;
            process.StartInfo.Arguments = $" {args.Trim()}";
            if (File.Exists(filePath))
            {
                process.StartInfo.WorkingDirectory = Path.GetDirectoryName(filePath);
            }

            process.StartInfo.CreateNoWindow = true;
            process.Start();
            process.Dispose();
        }

        /// <summary>
        /// 执行程序,返回结果
        /// </summary>
        /// <param name="filePath">程序路径</param>
        /// <param name="args">程序参数</param>
        public static string StartProgramWithResult(string filePath, string args = "")
        {
            string result = string.Empty;
            Process process = new Process();
            process.StartInfo.FileName = filePath;
            process.StartInfo.Arguments = $" {args.Trim()}";
            if (File.Exists(filePath))
            {
                process.StartInfo.WorkingDirectory = Path.GetDirectoryName(filePath);
            }

            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.UseShellExecute = false;
            process.Start();
            result = process.StandardOutput.ReadToEnd();
            if (string.IsNullOrWhiteSpace(result))
            {
                result = process.StandardError.ReadToEnd();
            }

            process.Dispose();
            return result;
        }

        /// <summary>
        /// 结束程序
        /// </summary>
        /// <param name="name">程序名称，不含后缀</param>
        public static void KillProgramByName(string name)
        {
            if (!string.IsNullOrWhiteSpace(name))
            {
                try
                {
                    Process[] processArray = Process.GetProcessesByName(name);
                    if (processArray != null)
                    {
                        foreach (Process item in processArray)
                        {
                            if (!item.HasExited)
                            {
                                try
                                {
                                    item.Kill();
                                }
                                catch { }
                            }
                        }
                    }
                }
                catch { }
            }
        }

        /// <summary>
        /// 加载json文件
        /// </summary>
        /// <param name="filePath">json文件路径</param>
        /// <returns></returns>
        public static JObject LoadJsonFile(string filePath)
        {
            using (StreamReader stream = new StreamReader(filePath, Encoding.UTF8))
            {
                string data = stream.ReadToEnd();
                return JObject.Parse(data);
            }
        }

        /// <summary>
        /// 保存文本
        /// </summary>
        /// <param name="content">文本数据</param>
        /// <param name="filePath">保存文件路径</param>
        public static void SaveFile(string content, string filePath)
        {
            using (StreamWriter sw = new StreamWriter(filePath, false, Encoding.UTF8))
            {
                sw.Write(content);
            }
        }

        /// <summary>
        /// 获取文件文本
        /// </summary>
        /// <param name="filePath">文件地址</param>
        public static string ReadFile(string filePath)
        {
            using (StreamReader stream = new StreamReader(filePath, Encoding.UTF8))
            {
                return stream.ReadToEnd();
            }
        }

        /// <summary>
        /// 执行sql,返回-1连接成功；其他数值为语句执行结果
        /// </summary>
        /// <param name="connection">连接字符串</param>
        /// <param name="sql">sql语句，isTest为true,此参数无效</param>
        /// <param name="isTest">测试链接</param>
        public static int ExecuteSql(string connection, string sql, bool isTest = false)
        {
            using (SqlConnection conn = new SqlConnection(connection))
            {
                conn.Open();
                if (isTest)
                {
                    return -1;
                }

                using (SqlCommand command = new SqlCommand(sql, conn))
                {
                    command.CommandType = CommandType.Text;
                    return command.ExecuteNonQuery();
                }
            }
        }
    }
}
